<% charts = chart.is_a?(Array) ? chart : [chart]
   stacked = charts.size > 1 %>
<% charts.each do |c| %>
  <% chart_name = c[:name] %>
  <div id="<%= chart_name %>_chart_container" class="chart_container">
    <% if stacked %>
      <strong><%= chart_name %></strong>
    <% end %>
    <div id="<%= chart_name %>_yaxis" class="y_axis"></div>
    <div id="<%= chart_name %>_chart" class="chart"></div>
    <div id="<%= chart_name %>_zoom" class="zoom"></div>
    <div id="<%= chart_name %>_legend" class="legend"></div>
  </div>
<% end %>

<script>
  var fn = function() {
    var palette = new Rickshaw.Color.Palette();
    var graphs = [];
    var graph, chart_div, data, startTime, endTime, timeStep, timeRange, metrics, currentTime;
    <% charts.each do |c| %>
      <% chart_name = c[:name] %>
      chart_div = document.getElementById("<%= chart_name %>_chart");
      <% c[:data] = c[:data].sort_by {|m| m['header']['metric']} %>
      data = JSON.parse('<%= sanitize(c[:data].to_json) -%>');
      if (data) {
        startTime = <%= c[:start_time] %>;
        endTime = <%= c[:end_time] %>;
        timeStep = <%= c[:step] %>;

        timeRange = [];
        currentTime = startTime;
        while (currentTime <= endTime) {
          timeRange.push(currentTime);
          currentTime = currentTime + timeStep;
        }

        metrics = data.map(function (metric) {
          var dataPoints = metric['data'];
          return {
            name: metric['header']['metric'],
            data: dataPoints.length ? timeRange.map(function (time, i) {
              return { x: time, y: dataPoints[i] };
            }) : [{x: timeRange[0], y: null}],
            color: palette.color()
          };
        });

        graph = new Rickshaw.Graph({
          element:     chart_div,
          renderer:    'line',
          interpolate: 'basis',
          series:      metrics
        });

        new Rickshaw.Graph.Axis.Time({graph: graph});

        new Rickshaw.Graph.Axis.Y({
          graph:       graph,
          orientation: 'left',
          tickFormat:  Rickshaw.Fixtures.Number.formatKMBT,
          element:     document.getElementById('<%= chart_name %>_yaxis')
        });

        new Rickshaw.Graph.Behavior.Series.Toggle({
          graph:  graph,
          legend: new Rickshaw.Graph.Legend({
            graph:   graph,
            element: document.getElementById('<%= chart_name %>_legend'),
            naturalOrder: true
          })
        });

        new Rickshaw.Graph.HoverDetail({
          graph:     graph,
          formatter: function (series, x, y) {
            return '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>' +
                series.name + ": " + y + "<br>" +
                '<span class="date">' + new Date(x * 1000).toTimeString() + '</span>';
          }
        });

        new Rickshaw.Graph.RangeSlider({
          graph:   graph,
          element: document.getElementById('<%= chart_name %>_zoom')
        });

        graphs.push(graph);
        graph.render();

        if (localStorage) {
          var disabledLinesKey = "oneops_monitor_chart_disabled_lines_" + "<%= chart_name %>";
          var disabledLines = localStorage.getItem(disabledLinesKey);
          if (disabledLines) {
            var item;
            $j("#<%= chart_name %>_legend .label").toArray().forEach(function(e) {
              item = $j(e);
              if (disabledLines.indexOf("~~~" + item.text() + "~~~") >= 0) {
                item.siblings(".action").click();
              }
            });
          }

          $j("#<%= chart_name %>_legend").find(".action, .label").click(function() {
            setTimeout(function() {
              var legend = $j("#<%= chart_name %>_legend"),
                  disabledItems = legend.find(".line.disabled .label"),
                  value = "~~~" + disabledItems.toArray()
                      .map(function (e) {
                             return $j(e).text();
                           })
                      .join("~~~") + "~~~";
              localStorage.setItem(disabledLinesKey, value);
            }, 100);
          });
        }
      }
      else {
        $j(chart_div).html("<%= escape_javascript(falied_loading_indicator('Failed to load chart data.')) %>");
      }
    <% end %>
  };
  fn();
</script>
